package com.sakura.oj.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sakura.oj.common.ErrorCode;
import com.sakura.oj.config.WxOpenConfig;
import com.sakura.oj.exception.BusinessException;
import com.sakura.oj.model.vo.LoginUserVO;
import com.sakura.oj.service.AuthStrategy;
import com.sakura.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 微信开放平台认证策略
 *
 * @author sakura
 */
@Slf4j
@Service(AuthStrategy.AUTH_BASE_KEY + "wx_open")
public class WxOpenAuthStrategy implements AuthStrategy {

    @Resource
    private WxOpenConfig wxOpenConfig;

    @Resource
    private UserService userService;

    @Override
    public LoginUserVO login(String data) {
        // 1. 解析
        JSONObject jsonObject = JSONUtil.parseObj(data);
        String code = jsonObject.get("code", String.class);
        if (StringUtils.isAnyBlank(code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数未传递");
        }
        WxOAuth2AccessToken accessToken;
        try {
            WxMpService wxService = wxOpenConfig.getWxMpService();
            accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo userInfo = wxService.getOAuth2Service().getUserInfo(accessToken, code);
            String unionId = userInfo.getUnionId();
            String mpOpenId = userInfo.getOpenid();
            if (StringUtils.isAnyBlank(unionId, mpOpenId)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
            }

            return null;
        } catch (Exception e) {
            log.error("userLoginByWxOpen error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
        }
    }
}
